<template>
    <div>
        <!-- 选择商品弹窗 -->
        <el-dialog title="添加商品" :visible.sync="showChooseProduct" :close-on-click-modal="false" 
            width="82%" @close="closeDialog" center append-to-body>
            <div class="goods_list">
                <div class="filter">
                    <el-form :model="queryParams" label-width="auto">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="关键词:">
                                    <el-input style="width: 200px;" maxlength="100" v-model="queryParams.search" placeholder="商品编号/商品名称" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item label="商品分类:">
                                    <el-cascader
                                        v-model="selectCates"
                                        :options="categorys"
                                        :show-all-levels="false"
                                        :props="{ checkStrictly: true, value: 'id', label: 'name' }"
                                        @change='itemChanged'
                                        style="width: 200px;"
                                        clearable>
                                    </el-cascader>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <div style="display: flex;align-items: center;justify-content: space-between;padding-right: 20px;">
                                    <div style="display: flex;align-items: center;" @click="showMore=!showMore">
                                        <span style="font-size: 14px;color: #606266;width: auto;cursor: pointer;margin-right: 5px;">高级搜索</span>
                                        <i :class="showMore?'el-icon-arrow-up':'el-icon-arrow-down'"></i>
                                    </div>
                                    <el-button size="small" icon="el-icon-search" @click="handleQuery"
                                        style="margin: 8px 0 0 20px;" class="btn_primary_color">查询</el-button>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row v-if="showMore">
                            <el-col :span="6">
                                <el-form-item label="状态:">
                                    <el-select style="width: 200px;" v-model="queryParams.status" placeholder="请选择" clearable>
                                        <el-option label="在售" value="active"></el-option>
                                        <el-option label="停售" value="inactive"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="品牌:">
                                    <el-input style="width: 200px;" v-model="queryParams.brand__icontains" placeholder="请输入" maxlength="20" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="规格:">
                                    <el-input style="width: 200px;" v-model="queryParams.specifications__icontains" placeholder="请输入" maxlength="20" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="型号:">
                                    <el-input style="width: 200px;" v-model="queryParams.type__icontains" placeholder="请输入" maxlength="20" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <el-table v-infinite-scroll="loadNextPage" :infinite-scroll-disabled="loadOver" ref="goodsTable"
                    :data="goodsList" border @selection-change="handleSelectionChange" style="margin-top: 15px;"
                    :infinite-scroll-distance="100" max-height="350">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="商品图片" align="center" width="100" prop="imageUrl">
                        <template slot-scope="scope">
                            <img :src="scope.row.imageUrl" style="width: 40px;height: 40px;" alt="">
                        </template>
                    </el-table-column>
                    <el-table-column label="商品名称" align="left" prop="name" />
                    <el-table-column label="商品编号" align="left" prop="goods_no" />
                    <el-table-column label="单价" align="left" prop="unit_price" />
                    <el-table-column label="单位" align="left" prop="unit" />
                    <el-table-column label="品牌" align="left" prop="brand" />
                    <el-table-column label="规格" align="left" prop="specifications" />
                    <el-table-column label="型号" align="left" prop="type" />
                    <el-table-column label="库存剩余" align="left" prop="current_inventory_quantity" />
                </el-table>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="btn_primary_color" @click="chooseGoodsOk">确 定</el-button>
                <el-button @click="closeDialog">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { listProduct, getTreeList } from '@/api/product';
export default {
    data() {
        return {
            queryParams: {
                status: '',
                brand__icontains: '',
                type__icontains: '',
                specifications__icontains: '',
                category_one_level: '',
                category: '',
                search: ''
            },
            categorys: [],
            selectCates: [],
            chooseGoods: [],
            middleGoods: [],
            goodsList: [],
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            loadOver: false,  //是否加载完
            showMore: false,
            corp: ''
        }
    },
    props: {
        showChooseProduct: {
            type: Boolean
        },
        selectGoods: {
            type: Array
        },
        isMultiple: {
            type: Boolean,
            default: true
        }
    },
    watch: {
        selectGoods: {
            handler(newVal) {
                // 当 selectGoods 变化时执行的操作
                console.log('selectGoods 已更新', newVal);
                this.middleGoods = newVal
                this.handleSelectRow()
            },
            deep: true // 深度监听数组变化
        }
    },
    created() {
        this.corp = this.$store.state.corpId
        this.getProductCategory()
        this.handleQuery()
    },
    methods: {
        // 获取商品分类
        getProductCategory() {
            let that = this
            getTreeList({corp: this.corp}).then(res => {
                let categorys = res.data.data.category_list.filter(item => { return !item.parent })
                that.categorys = categorys
            })
        },
        // 分类点击
        itemChanged(val) {
            if (val && val.length>0){
                if (val.length === 1){
                    this.queryParams.category_one_level = val[0]
                    this.queryParams.category = null
                }else if (val.length === 2){
                    this.queryParams.category_one_level = null
                    this.queryParams.category = val[1]
                }
            }else{
                this.queryParams.category_one_level = null
                this.queryParams.category = null
            }
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            if (!this.isMultiple && selection.length>1){  //单选
                let that = this
                this.$nextTick(() => {
                    const table = that.$refs.goodsTable;
                    if (table && table.toggleRowSelection) {
                        table.clearSelection();
                        table.toggleRowSelection(selection[selection.length-1], true);
                    }
                })
            }else{
                this.chooseGoods = selection
            }
        },
        // 加载下一页数据
        loadNextPage() {
            // 禁用滚动加载
            this.loadOver = true;
            let allPage = 0
            if (this.total === 0) return
            
            if (this.total % this.pageParam.num === 0){  //整除
                allPage = Math.trunc(this.total / this.pageParam.num)
            }else{
                allPage = Math.trunc(this.total / this.pageParam.num) + 1
            }
            console.log(allPage, this.pageParam.page)
            this.pageParam.page ++
            // this.loadOver = false
            if (this.pageParam.page > allPage){
                this.loadOver = true
                return
            }
            this.middleGoods = this.chooseGoods
            this.getProductLists()
        },
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.goodsList = []
            this.loadOver = false
            this.getProductLists()
        },
        // 获取商品列表
        getProductLists() {
            let that = this
            this.queryParams.corp = this.corp
            let params = Object.assign({}, this.queryParams, this.pageParam)
            listProduct(params).then(res => {
                let list = res.data.data.good_list.filter(item => {
                    item.cateName = item.category_detail.name
                    if (item.image_show && item.image_show.url){
                        item.imageUrl = item.image_show.url
                    }else{
                        item.imageUrl = 'https://anhuiyaoying.com/icon/default.png'
                    }
                    item.select_num = 0,
                    item.goods_no = item.goods_no || ''
                    item.specifications = item.specifications || ''
                    item.unit_purchase_price = item.unit_purchase_price?parseFloat(item.unit_purchase_price):'0'
                    item.unit_price = item.unit_retail_price?parseFloat(item.unit_retail_price):'0'
                    item.current_inventory_quantity = parseFloat(item.current_inventory_quantity)
                    return item
                })
                that.goodsList = that.goodsList.concat(list)
                that.total = res.data.data.total
                // 合并已选数据
                that.joinArray()
                // 勾选已选择行
                that.handleSelectRow()
                // 启用滚动加载
                that.loadOver = false;
            })
        },
        joinArray() {
            const map = new Map();
            this.goodsList.forEach(item => {
                map.set(item.id, { ...item });
            });

            this.selectGoods.forEach(item => {
                if (map.has(item.id)) {
                    const existingItem = map.get(item.id);
                    map.set(item.id, { ...existingItem, ...item });
                } else {
                    map.set(item.id, { ...item });
                }
            });
            this.goodsList = Array.from(map.values());
        },
        handleSelectRow() {
            let that = this
            this.$nextTick(() => {
                const table = that.$refs.goodsTable;
                if (table && table.toggleRowSelection) {
                    table.clearSelection();
                    that.middleGoods.forEach(item => {
                        const rowToSelect = that.goodsList.find(order => order.id === item.id);
                        if (rowToSelect) {
                            table.toggleRowSelection(rowToSelect, true);
                        }
                    })
                }
            })
        },
        closeDialog() {
            this.chooseGoods = []
            this.$emit('hidden')
        },
        chooseGoodsOk() {
            let res = this.chooseGoods
            this.middleGoods = res
            this.$emit('chooseOK', res)
            this.chooseGoods = []
        },
    }
}
</script>

<style scoped>
    .goods_list {
        padding: 0 10px;
        max-height: 460px;
        overflow-y: auto;
    }
    .btn_primary_color {
        background: #0099ff !important;
        color: #fff !important;
    }
</style>